package com.xuecheng.govern.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.xuecheng.framework.model.response.CommonCode;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.govern.gateway.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginFilter extends ZuulFilter {

    @Autowired
    AuthService authService;
    /**
     * 返回字符串代表过滤器的类型，如下
     * ​	pre：请求在被路由之前执行
     * ​	routing：在路由请求时调用
     * ​	post：在routing和errror过滤器之后调用
     * ​	error：处理请求时发生错误调用
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    /**
     * 通过返回值来定义过滤器的执行顺序，数字越小优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 返回true 表示执行该过滤器
     *    false  表示不执行该过滤器
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    //过滤器业务逻辑
    @Override
    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        //1. 从请求头中获取jwt令牌
        String jwtToken = authService.getJwtTokenFromHeader(request);
        //2. 从cookie中获取用户jti短令牌
        String jti_Token = authService.getTokenFromCookie(request);
        //3. 查询redis中令牌是否过期
        long expireOfToken = authService.getExpireOfToken(jti_Token);

        if (StringUtils.isEmpty(jwtToken)
            || StringUtils.isEmpty(jti_Token)
            || expireOfToken < 0) {
            //拒绝访问
            this.accessDeny();
        }
        return null;
    }

    private void accessDeny() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        // 拒绝访问
        requestContext.setSendZuulResponse(false);
        // 设置响应状态码
        requestContext.setResponseStatusCode(200);
        //设置响应结果
        ResponseResult unauthenticated = new ResponseResult(CommonCode.UNAUTHENTICATED);
        String jsonString = JSON.toJSONString(unauthenticated);
        requestContext.setResponseBody(jsonString);
        response.setContentType("application/json;charset=UTF-8");
    }
}
